<template>
	<view class="body">
		<view>
			<view class="orderInfo">
				<view class="order" v-for="item of obj.itemListVoList">
					<image :src="item.itemImg ? item.itemImg :'../../static/images/anmo.png'" class="shop_img">
					</image>
					<view class="name">
						<view class="txt">
							{{ item.itemName }}
						</view>
						<view class="txt sty">
							数量：1
						</view>
						<view class="txt sty">
							时长：{{ item.itemDuration || 0 }}分钟
						</view>
					</view>
					<view class="price">
						￥{{ item.itemPrice }}
					</view>
				</view>
				<view class="coupon">
					<view class="title">
						优惠卷：
					</view>
					<view class="name">
						{{ couponName }}
					</view>
					<view class="price">
						{{ couponPrice }}
					</view>
				</view>
				<view class="coupon" style="margin-bottom: 140upx;">
					<view class="title">
						促销活动：
					</view>
					<view class="name">
						{{ promotionName }}
					</view>
					<view class="price">
						{{ promotionMoney }}
					</view>
				</view>
			</view>
			<view class="btn">
				<view class="shop_bt">
					<view class="shop_bt_left">
						<text>合计:</text>￥{{ payOrderObj.needEntryMoney }}
					</view>
					<view class="shop_bt_right" @click="openSubmit">
						立即支付
					</view>
				</view>
			</view>
			<u-popup :show="show" @close="show = false" :round="10" mode="bottom">
				<view class="paySelect">
					<view class="weixin pay" @click="submit">
						<u-icon name="weixin-circle-fill" size="50px" color="#2CAC68"></u-icon>
						微信支付
					</view>
					<view class="memberCard pay" @click="goMemberPay">
						<u-icon name="rmb-circle-fill" size="50px" color="#E1AC2C"></u-icon>
						会员卡支付
					</view>
				</view>

			</u-popup>
			<u-popup :show="memberzhifu" @close="memberzhifu = false" :round="10" mode="bottom">
				<view class="memberPayInfo">
					<view class="top">
						<view class="card">
							<view class="item cardName">
								{{ memberInfo.memberCardType }}
							</view>
							<view class="item" style="color:#FFD077;">
								{{ memberInfo.cardNumber }}
							</view>
						</view>
						<view class="info">
							<view class="item">
								账面余额:
								<span style="color: red;"> ￥{{ memberInfo.paperAmount }}</span>
							</view>
							<view class="item">
								实际余额:
								<span style="color: red;"> ￥{{ memberInfo.infactAmount }}</span>
							</view>
							<view class="item">
								赠送余额:
								<span style="color: red;"> ￥{{ memberInfo.giveAmount }}</span>
							</view>
						</view>
					</view>
					<view class="radio">
						<u-checkbox-group v-model="memberCheckboxs" placement="row" iconPlacement="right"
							@change="memberCheckbox">
							<u-checkbox name="0" shape="circle" label="会员折扣优惠"></u-checkbox>
							<u-checkbox name="1" shape="circle" label="会员价优惠"></u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="from">
						<view class="item">
							实际支付：
							<u-input v-model="memberPayInfo.infactFinalMoney" @input="infactFinalInput"></u-input>
						</view>
						<span>{{ infactText }}</span>
						<view class="item">
							赠送支付：
							<u-input v-model="memberPayInfo.giveFinalMoney" @input="giveFinalInput"></u-input>
						</view>
						<span>{{ giveText }}</span>
					</view>
					<view class="btn">
						<view class="shop_bt">
							<view class="shop_bt_left">
								<text>剩余应付:</text>￥{{ residueMoney }}
							</view>
							<view class="shop_bt_right" @click="memberPay">
								立即支付
							</view>
						</view>
					</view>
				</view>
			</u-popup>
			<u-picker :show="pickerShow" :columns="memberInfoList" keyName="nameCardNum" @confirm="confirm"
				@cancel="pickerShow = false" title="请选择您的会员卡">
			</u-picker>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				requesturl: 'https://server.xinguanjia.net',
				obj: {
					itemListVoList: []
				},
				search: {
					customerId: '',
					customerOpenOrderId: null,
					code: null,
					cashierItemReqList: []
				},
				payOrderObj: {
					receivableMoney: 0,
				},
				orderBillCouponReqList: [],
				show: false,
				memberzhifu: false,
				memberInfoList: [], // 所有的会员卡列表
				memberInfo: {}, // 选中的会员卡
				pickerShow: false,
				memberPayInfo: {
					freeConfidentiality: true,
					enjoyMemberDiscount: 0,
					enjoyMemberPrice: 0,
					giveFinalMoney: 0,
					infactFinalMoney: 0,
					paymentMoney: 0,
					// memberCardId: '',
					customerId: '',
				},
				radiolist: [{
						name: '会员价优惠',
						disabled: false
					},
					{
						name: '会员折扣优惠',
						disabled: false
					},
				],
				radiovalue: '会员价优惠',
				formData: {}, // 会员卡的设置
				memberCheckboxs: [],
				infactText: '',
				giveText: '',
				loading: false,
			}
		},
		onLoad(val) {
			// setTimeout(()=>{
			// 	this.loading = true
			// },1000)
			this.id = val.orderId
			this.search.customerOpenOrderId = val.orderId
			this.search.code = uni.getStorageSync('code')
			this.search.customerId = uni.getStorageSync('customerId')
			this.memberPayInfo.customerId = uni.getStorageSync('customerId')
			this.$get(this.$api.customerMemberList, {
				customerId: uni.getStorageSync('customerId')
			}, res => {
				console.log(res);
				res.data = res.data.map(item => {
					return {
						...item,
						nameCardNum: item.memberCardType + ` (${item.cardNumber}) `
					}
				})
				this.memberInfoList = [res.data]
			}, err => {
				console.log(err);
			}, 1, 0)

			this.init()
			this.getMemberCardSetting()
		},
		computed: {
			// 优惠劵名称
			couponName() {
				return !!this.payOrderObj?.orderBillCouponReq ? this.payOrderObj.orderBillCouponReq.couponName : ''
			},
			// 优惠金额
			couponPrice() {
				return !!this.payOrderObj?.preferentialMoney ? '￥' + this.payOrderObj.preferentialMoney : '暂无可用'
			},
			// 促销金额
			promotionMoney() {
				return !!this.payOrderObj?.itemActivityPromotionMemberMoney ? this.payOrderObj
					.itemActivityPromotionMemberMoney : '暂无可用'
			},
			// 促销活动名称
			promotionName() {
				return !!this.payOrderObj?.itemActivityPromotionName ? this.payOrderObj.itemActivityPromotionName : ''
			},
			// 当前会员卡应付金额
			amountPayable() {
				return
			},
			// 会员剩余应付
			residueMoney() {
				return (Math.round((this.payOrderObj.needEntryMoney - this.memberPayInfo.infactFinalMoney - this
					.memberPayInfo.giveFinalMoney) * 100) / 100).toFixed(2)
			}
		},
		watch: {
			'memberInfo': {
				handler(newVal) {
					console.log(newVal)
				},
				immediate: true,
				deep: true,
			},
			'formData.payDisountable': {
				handler(newVal) {
					switch (newVal) {
						case 0:
							this.memberPayInfo.enjoyMemberDiscount = 1
							this.memberPayInfo.enjoyMemberPrice = 1
							this.memberCheckboxs = []
							break;
						case 1:
							this.memberPayInfo.enjoyMemberDiscount = 1
							this.memberPayInfo.enjoyMemberPrice = 0
							this.memberCheckboxs = ['1']
							break;
						case 2:
							this.memberPayInfo.enjoyMemberDiscount = 0
							this.memberPayInfo.enjoyMemberPrice = 1
							this.memberCheckboxs = ['0']
							break;
						case 3:
							this.memberPayInfo.enjoyMemberDiscount = 0
							this.memberPayInfo.enjoyMemberPrice = 0
							this.memberCheckboxs = ['0', '1']
							break;
					}

				},
				immediate: false,
				deep: true,
			},
			memberzhifu(newVal) {
				if (!newVal) {
					this.getPayOrderMoney('0')
				} else {
					this.calculateMoney()
				}
			}
		},
		methods: {
			// 获取订单信息以及买单金额
			init() {
				new Promise((resolve, rejecte) => {
					this.$post(this.$api.getCustomerOpenOrderItemByPay, {
							customerOpenOrderId: this.id
						},
						(res) => {
							this.obj = res.data
							this.search.cashierItemReqList = res.data.itemListVoList.map(item => {
								return {
									sendLockPlateId: item.sendLockPlateId,
									memberDiscounts: true,
									lockPlateBillingItemId: item.lockPlateBillingItemId,
								}
							})
							resolve()
						}, (res) => {
							this.handleError(res);
							reject();
						}, 1, 0)
				}).then(() => {
					// this.getMemberCardSetting()
					this.getPayOrderMoney('0')
				})
			},
			// 计算金额
			calculateMoney() {
				this.getPayOrderMoney('1').then(res => {
					let {
						paperAmount,
						infactAmount,
						giveAmount,
						createTime
					} = this.memberInfo
					let {
						maxGiveFinalMoney,
						maxInfactFinalMoney,
						receivableMoney,
						needEntryMoney
					} = res
					let {
						addConsume,
						payDisountable,
						payType
					} = this.formData
					// addConsume
					// 会员开卡当天消费比例

					// payDisountable
					// label="会员价和会员折扣都不享受" :value="0"
					// label="享受会员价" :value="1"
					// label="享受会员折扣" :value="2"
					// label="会员价和会员折扣都享受" :value="3"

					// payType
					// label="扣款比例" :value="0"
					// label="先扣实收" :value="1"
					// label="先扣赠送" :value="2"

					let money = paperAmount > needEntryMoney ? needEntryMoney : paperAmount
					let oldTime = new Date(createTime?.slice(0, 11));
					let newTime = new Date();
					if (
						newTime.getDate() === oldTime.getDate() &&
						newTime.getMonth() === oldTime.getMonth() &&
						newTime.getFullYear() === oldTime.getFullYear() &&
						addConsume
					) {
						// 当天开卡可用金额打折扣
						paperAmount = (paperAmount * addConsume) / 100;
						infactAmount = (infactAmount * addConsume) / 100;
						giveAmount = (giveAmount * addConsume) / 100;
					}
					let infact = 0
					let give = 0
					if (payType === 0) {
						console.log('按扣款比例')
						const ratio = Math.round((infactAmount / paperAmount) * 100) / 100
						infact = (Math.round((money * ratio) * 100) / 100).toFixed(2)
						infact = maxInfactFinalMoney > infact ? infact : maxInfactFinalMoney
						give = (Math.round((money - infact) * 100) / 100).toFixed(2)
						give = maxGiveFinalMoney > give ? give : maxGiveFinalMoney
					} else if (payType === 1) {
						console.log('先扣实际')
						let a = needEntryMoney > infactAmount ? infactAmount : needEntryMoney
						infact = a > maxInfactFinalMoney ? maxInfactFinalMoney : a
						give = infact === needEntryMoney ? 0 : needEntryMoney - infact
					} else if (payType === 2) {
						console.log('先扣赠送')
						let a = needEntryMoney > giveAmount ? giveAmount : needEntryMoney
						give = a > maxGiveFinalMoney ? maxGiveFinalMoney : a
						infact = give === needEntryMoney ? 0 : needEntryMoney - give
					}
					this.memberPayInfo.infactFinalMoney = infact
					this.memberPayInfo.giveFinalMoney = give
				})
			},
			// 获取买单金额
			getPayOrderMoney(str) {
				const req = JSON.parse(JSON.stringify(this.search))
				if (str === '1') {
					req.memberCardList = [JSON.parse(JSON.stringify(this.memberPayInfo))]
				}
				return new Promise((resolve, reject) => {
					this.$post(this.$api.getCashierMoneyAutoCountCoupons, req,
						(res) => {
							this.payOrderObj = res.data
							this.orderBillCouponReqList = JSON.parse(JSON.stringify(res.data
								.orderBillCouponReq))
							resolve(res.data)
						}, (res) => {
							this.handleError(res);
							reject()
						}, 1, 0)
				})

			},
			// 获取会员设置信息
			getMemberCardSetting() {
				this.$get(this.$api.cardSetting, {},
					(res) => {
						if (res.data === null) return;
						console.log(res.data);
						this.formData = res.data;
					}, err => {
						console.log(err.msg);
					}, 1, 0)
			},
			// 选择会员优惠
			memberCheckbox(n) {
				if (n.includes('0') && n.includes('1')) {
					this.memberPayInfo.enjoyMemberDiscount = 0
					this.memberPayInfo.enjoyMemberPrice = 0
				} else if (n.includes('0')) {
					this.memberPayInfo.enjoyMemberDiscount = 0
					this.memberPayInfo.enjoyMemberPrice = 1
				} else if (n.includes('1')) {
					this.memberPayInfo.enjoyMemberDiscount = 1
					this.memberPayInfo.enjoyMemberPrice = 0
				} else if (n.length === 0) {
					this.memberPayInfo.enjoyMemberDiscount = 1
					this.memberPayInfo.enjoyMemberPrice = 1
				}
				this.calculateMoney()
			},
			// 打开支付选择界面
			openSubmit() {
				this.show = true
			},
			// 去会员卡支付
			goMemberPay() {
				if (this.memberInfoList[0].length > 0) {
					this.pickerShow = true
				} else {
					uni.showToast({
						title: "您当前暂无会员卡",
						icon: 'none'
					});
				}
			},
			// 会员金额的输入事件
			// 赠送金额
			giveFinalInput(val) {
				console.log(+val, 'val2');
				const money = +this.payOrderObj.maxGiveFinalMoney > +this.memberInfo.infactAmount ? +this.memberInfo
					.infactAmount : +this.payOrderObj.maxGiveFinalMoney
				if (+val < 0) {
					this.memberPayInfo.giveFinalMoney = 0
				}
				if (+val > +money) {
					this.memberPayInfo.giveFinalMoney = money
					this.giveText = `当前订单的最大可用赠送支付金额为 ${money} 元`
				} else {
					this.giveText = ''
				}
			},
			// 实际金额
			infactFinalInput(val) {
				console.log(+val, 'val2');
				const money = +this.payOrderObj.maxInfactFinalMoney > +this.memberInfo.infactAmount ? +this.memberInfo
					.infactAmount : +this.payOrderObj.maxInfactFinalMoney
				if (+val < 0) {
					this.memberPayInfo.infactFinalMoney = 0
				}
				if (+val > +money) {
					this.memberPayInfo.infactFinalMoney = money
					this.infactText = `当前订单的最大可用实际支付金额为 ${money} 元`
				} else {
					this.infactText = ''
				}
			},
			// 选择会员卡
			confirm(val) {
				console.log(val, 'val');
				if (val) {
					this.memberInfo = val.value[0]
					this.memberPayInfo.memberCardId = val.value[0].memberId
					this.pickerShow = false
					this.memberzhifu = true
				}
			},
			// 会员支付
			memberPay() {
				// if(this.residueMoney !== 0) return uni.showToast({title: '请填写正确的金额',icon: 'none'})
				const req = JSON.parse(JSON.stringify(this.search))
				this.memberPayInfo.paymentMoney = +this.memberPayInfo.infactFinalMoney + +this.memberPayInfo.giveFinalMoney
				req.memberCardList = [this.memberPayInfo]
				uni.showLoading({
					title: '正在支付中...',
				})
				new Promise((resolve, reject) => {
					this.$post(this.$api.getCashierMoneyAutoCountCoupons, req,
						(res) => {
							if (res.data.receivableMoney === 0) {
								resolve(res.data)
							} else {
								uni.showToast({
									title: '请填写正确的金额',
									icon: 'none'
								})
								uni.hideLoading()
							}
						}, (res) => {
							uni.hideLoading()
							this.handleError(res);
							reject()
						}, 1, 0)
				}).then(() => {
					this.$post(this.$api.customerMemberCardPayOrder, req,
						(res) => {
							if (res.code === 200) {
								uni.hideLoading()
								uni.showToast({
									title: '支付成功',
								})
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/order/index'
									})
								}, 300)
							}
						}, res => {
							uni.hideLoading()
							this.handleError(res);
						}, 1, 0)
				})
			},
			// 微信支付
			submit() {
				const req = JSON.parse(JSON.stringify(this.search))
				req.orderBillCouponReqList = this.orderBillCouponReqList
				this.$post(this.$api.customerWxPayOrder, req,
					(res) => {
						console.log(res, 'res');
						if (res.code !== 200) return
						if (res.code == 200) {
							//微信支付//WX JSAPI
							WeixinJSBridge.invoke(
								'getBrandWCPayRequest', {
									"appId": res.data.appId, //公众号名称，由商户传入     
									"timeStamp": res.data.timeStamp, //时间戳，自1970年以来的秒数     
									"nonceStr": res.data.nonceStr, //随机串     
									"package": res.data.pack, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
									"signType": res.data.signType, // 签名方式，
									"paySign": res.data.paySign, //微信签名  
								},
								function(res) {
									// 支付成功
									if (res.err_msg == "get_brand_wcpay_request:ok") {
										uni.showToast({
											title: '支付成功'
										})
										uni.switchTab({
											url: '/pages/order/index'
										})
										this.list = [];
										this.money = 0;
										this.btn_view = false;
									}
									// 支付过程中用户取消
									if (res.err_msg == "get_brand_wcpay_request:cancel") {
										uni.showToast({
											title: '取消支付,请重新支付',
											icon: 'none'
										})
									}
									// 支付失败
									if (res.err_msg == "get_brand_wcpay_request:fail") {
										uni.showToast({
											title: '支付失败，请重新支付',
											icon: 'none'
										})
									}
									/**
									 * 其它
									 * 1、请检查预支付会话标识prepay_id是否已失效
									 * 2、请求的appid与下单接口的appid是否一致
									 * */
									if (res.err_msg == "调用支付JSAPI缺少参数：total_fee") {
										uni.showToast({
											title: '调用支付JSAPI缺少参数',
											icon: 'none'
										})
									}
								})
						} else {
							this.handleError(res);
						}
					}, (res) => {
						this.handleError(res);
					}, 1, 0)
			},
			// 错误处理函数
			handleError(res) {
				uni.hideLoading();
				uni.showToast({
					title: res.msg ? res.msg : '网络错误',
					icon: 'none'
				});
			},
		}
	}
</script>

<style lang="less" scoped>
	.body {
		.btn {
			margin: 10upx 0;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			position: fixed;
			bottom: 0;
			left: 0;

			.shop_bt {
				width: 90%;
				height: 90upx;
				line-height: 90upx;
				border-radius: 100upx;
				background-color: #333;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.shop_bt_left {
					display: flex;
					align-items: center;
					width: 70%;
					height: 100%;
					font-size: 35upx;
					text-indent: 30upx;

					text {
						font-size: 28upx;
						color: rgb(209, 124, 47);
					}
				}

				.shop_bt_right {
					width: 30%;
					height: 100%;
					background-color: #07c160;
					border-radius: 0 100upx 100upx 0;
					text-align: center;
				}
			}
		}

		.orderInfo {
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.coupon {
				width: 90%;
				display: flex;
				margin: 10upx 0;
				padding: 20upx;
				justify-content: space-around;
				align-items: center;
				background-color: #fff;
				border-radius: 10upx;

				.title {
					font-size: 30upx;
					font-weight: 600;
				}

				.name {}

				.price {
					font-size: 24upx;
					color: #999;
				}
			}

			.order {
				background-color: #fff;
				width: 90%;
				display: flex;
				margin: 10upx 0;
				padding: 20upx;
				border-radius: 10upx;

				.shop_img {
					width: 150upx;
					height: 150upx;
				}

				.name {
					width: 50%;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: ;
					margin-left: 10%;
					font-size: 28upx;
					font-weight: 600;

					.txt {
						margin: 10upx 0;
					}

					.sty {
						font-size: 24upx;
						font-weight: 400;
						color: #999;
					}
				}

				.price {
					color: red;
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
				}
			}
		}

		.paySelect {
			height: 200upx;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.pay {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				font-weight: 500;
			}
		}

		.memberPayInfo {
			display: flex;
			flex-direction: column;
			align-items: center;
			height: 900upx;

			.radio {
				height: 100upx;
				width: 80%;
				display: flex;
				justify-content: flex-start;
				align-items: center;
			}

			.top {
				width: 90%;
				margin: 20upx 0;
				background-color: #fff;
				display: flex;
				justify-content: space-around;
				align-items: center;
				border-radius: 15upx;

				.card {
					margin: 20upx 0;
					width: 300upx;
					height: 200upx;
					background-image: url('../../static/images/card_vip3.png');
					background-repeat: no-repeat;
					background-size: cover;
					border-radius: 20upx;
					display: flex;
					flex-direction: column;
					justify-content: center;

					.item {
						color: #fff;
						margin: 15upx 50upx;
						font-size: 32upx;
						font-weight: 500;

						span {
							margin-left: 20upx;
						}
					}

					.cardName {
						font-size: 36upx;
						font-weight: 600;
					}
				}

				.info {
					flex: 0.8;

					.item {
						font-size: 28upx;
						margin: 10upx 0;
					}
				}
			}

			.from {
				width: 90%;
				margin: 20upx 0;
				background-color: #fff;
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				align-items: center;
				border-radius: 15upx;

				.item {
					margin: 20upx 0;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				span {
					color: red;
					font-size: 26upx;
				}
			}

			.btn {
				margin: 10upx 0;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				position: fixed;
				bottom: 0;
				left: 0;

				.shop_bt {
					width: 90%;
					height: 90upx;
					line-height: 90upx;
					border-radius: 100upx;
					background-color: #333;
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.shop_bt_left {
						display: flex;
						align-items: center;
						width: 70%;
						height: 100%;
						font-size: 35upx;
						text-indent: 30upx;

						text {
							font-size: 28upx;
							color: rgb(209, 124, 47);
						}
					}

					.shop_bt_right {
						width: 30%;
						height: 100%;
						background-color: #07c160;
						border-radius: 0 100upx 100upx 0;
						text-align: center;
					}
				}
			}
		}
	}
</style>